<template>
	<view class="container">
		<!-- 空状态栏占位 -->
		<view class="status-bar"></view>
		
	<!-- 头部区域 -->

		
		<!-- 搜索栏 -->
			<view class="search-bar">
			<view class="search-input">
				<text class="search-icon">🔍</text>
				<input type="text" placeholder="资产名称或报修单号" v-model="searchKeyword" @input="onSearchInput" />
			</view>
		</view>
		
		<!-- 记录列表 -->
		<view class="drafts-list">
			<view class="draft-item" v-for="(record, index) in filteredRecords" :key="index" :data-index="index" @touchstart="onTouchStart" @touchmove="onTouchMove" @touchend="onTouchEnd" :style="{ transform: `translateX(${record.translateX}px)` }">
				<view class="draft-content" @click="viewRecord(record)">
					<view class="draft-header">
						<text class="draft-title">{{ record.orderNo || '暂无单号' }}</text>
						<view class="status-badge acknowledged">
							<text class="status-text">{{ getStatusText(record.status) }}</text>
		</view>
					</view>
					<view class="draft-info">
						<text class="info-item">资产名称: {{ record.assetName }}</text>
						<text class="info-item">资产位置: {{ record.assetLocation }}</text>
						<text class="info-item">发生时间: {{ record.occurrenceTime }}</text>
					</view>
					<view class="draft-footer">
					<view class="reporter-info">
						<image class="reporter-avatar" :src="record.reporterAvatar || '/static/个人头像.png'"></image>
						<text class="reporter-name">{{ record.reporterName }}</text>
						</view>
						<text class="report-time">报修时间: {{ record.reportTime }}</text>
					</view>
				</view>
                <view class="swipe-actions">
                    <!-- 隐藏“查看”按钮，点击卡片直接进入详情 -->
                    <!-- <button class="swipe-btn view" @click.stop="viewRecord(record)">查看</button> -->
					<!-- 维修主管只能看到维修指派按钮 -->
					<button 
						v-if="isMaintenanceManager() && canAssign(record)" 
						class="swipe-btn assign" 
						@click.stop="handleAssign(record)"
					>
						维修指派
					</button>
					<!-- 非维修主管可以看到其他按钮 -->
					<button 
						v-if="!isMaintenanceManager() && record.status === 'CONFIRMED'" 
						class="swipe-btn acknowledge" 
						@click.stop="acknowledgeRecord(record, index)"
					>
						承认
					</button>
					<button 
						v-if="!isMaintenanceManager() && record.status === 'CONFIRMED'" 
						class="swipe-btn reject" 
						@click.stop="rejectAcknowledge(record, index)"
					>
						拒绝承认
					</button>
					<button 
						v-if="!isMaintenanceManager() && record.status === 'ACKNOWLEDGED'" 
						class="swipe-btn delete" 
						@click.stop="deleteRecord(record, index)"
					>
						删除
					</button>
				</view>
				</view>
			</view>
			
			<!-- 空状态 -->
			<view class="empty-state" v-if="filteredRecords.length === 0">
				<text class="empty-icon">📋</text>
			<text class="empty-text">暂无报修记录</text>
		</view>
	</view>
</template>

<script>
	import { listFaultReport, delFaultReport, acknowledgeFaultReport, rejectFaultReport } from '@/api/repair/faultReport.js';
	import permissionManager from '@/utils/permission.js';
	
	export default {
		data() {
			return {
				searchKeyword: '',
				records: [],
				touchStartX: 0,
				touchStartY: 0,
				loading: false
			}
		},
		computed: {
			filteredRecords() {
				if (!this.searchKeyword) {
					return this.records;
				}
				return this.records.filter(record => 
					(record.assetName && record.assetName.toLowerCase().includes(this.searchKeyword.toLowerCase())) ||
					(record.reportNo && record.reportNo.toLowerCase().includes(this.searchKeyword.toLowerCase()))
				);
			}
		},
		onLoad() {
			this.checkLoginStatus();
			this.loadRecords();
		},
		onShow() {
			// 检查是否需要刷新
			const needRefresh = uni.getStorageSync('needRefreshRecords');
			if (needRefresh) {
				this.loadRecords();
				uni.removeStorageSync('needRefreshRecords');
			}
		},
		methods: {
			// 检查登录状态
			checkLoginStatus() {
				const token = uni.getStorageSync('token');
				if (!token) {
					uni.showModal({
						title: '提示',
						content: '请先登录',
						showCancel: false,
						success: () => {
							uni.reLaunch({
								url: '/pages/login/login'
							});
						}
					});
				}
			},
			
			// 搜索输入
			onSearchInput() {
				// 实时过滤，无需额外处理
			},
			
			// 加载报修记录列表
			async loadRecords() {
				if (this.loading) return;
				
				this.loading = true;
				try {
					const res = await listFaultReport({
						pageNum: 1,
						pageSize: 100
					});
					
					if (res && res.code === 200 && res.rows) {
						// 显示所有数据
						const userReports = res.rows;
						
						this.records = userReports.map(item => ({
							reportNo: item.reportNo,
							orderNo: item.reportNo,
							assetNo: item.assetNo,
							assetName: item.assetName,
							assetLocation: item.location,
							occurrenceTime: item.occurTime,
							reporterName: item.reporter,
							reporterAvatar: '/static/个人头像.png',
							reportTime: item.reportTime || item.createTime,
							faultDescription: item.faultDescription,
							status: item.status,
							translateX: 0
						}));
						
						console.log('报修记录加载完成，共', this.records.length, '条');
					}
				} catch (error) {
					console.error('加载报修记录失败:', error);
				uni.showToast({
						title: '加载失败',
					icon: 'none'
				});
				} finally {
					this.loading = false;
				}
			},
			
			// 触摸开始
			onTouchStart(e) {
				this.touchStartX = e.touches[0].clientX;
				this.touchStartY = e.touches[0].clientY;
			},
			
			// 触摸移动
			onTouchMove(e) {
				const currentX = e.touches[0].clientX;
				const currentY = e.touches[0].clientY;
				const deltaX = currentX - this.touchStartX;
				const deltaY = currentY - this.touchStartY;
				
				// 如果纵向滑动大于横向滑动，则不处理
				if (Math.abs(deltaY) > Math.abs(deltaX)) {
					return;
				}
				
				// 从 data-index 获取索引
				const index = parseInt(e.currentTarget.dataset.index);
				
				if (!isNaN(index) && index >= 0 && index < this.filteredRecords.length) {
					// 限制滑动范围
					let translateX = deltaX;
					if (translateX > 0) translateX = 0;
					if (translateX < -120) translateX = -120;
					
					this.$set(this.records[index], 'translateX', translateX);
				}
			},
			
			// 触摸结束
			onTouchEnd(e) {
				const currentX = e.changedTouches[0].clientX;
				const deltaX = currentX - this.touchStartX;
				
				// 从 data-index 获取索引
				const index = parseInt(e.currentTarget.dataset.index);
				
				if (!isNaN(index) && index >= 0 && index < this.filteredRecords.length) {
					const record = this.filteredRecords[index];
					// 如果滑动距离超过60px，显示操作按钮
					if (deltaX < -60) {
						this.$set(record, 'translateX', -120);
					} else {
						this.$set(record, 'translateX', 0);
					}
				}
			},
			
			// 查看报修记录详情
			viewRecord(record) {
				if (!record.reportNo) {
					uni.showToast({
						title: '记录数据异常',
						icon: 'none'
					});
					return;
				}
				uni.navigateTo({
					url: `/pages/repair/detail?reportNo=${record.reportNo}`
				});
			},
			
			// 获取状态文本
			getStatusText(status) {
				const statusMap = {
					'DRAFT': '草稿',
					'PENDING_ASSIGN': '待分配',
					'PENDING_ACKNOWLEDGE': '待承认',
					'ACKNOWLEDGED': '已承认',
					'COMPLETED': '待承认', // 将已完成状态显示为待承认
					'IN_PROGRESS': '进行中',
					'ASSIGNED': '已分配',
					'PENDING_EXEC': '待维修',
					'IN_REPAIR': '维修中',
					'WAITING_MATERIAL': '待料中',
					'EXTRA_PROCESSING': '追加工中',
					'PENDING_CONFIRM': '待确认',
					'CONFIRMED': '已确认',
					'REJECTED': '拒绝确认'
				};
				return statusMap[status] || status || '未知';
			},
			
			// 承认报修记录
			acknowledgeRecord(record, index) {
				uni.showModal({
					title: '确认承认',
					content: `确定要承认报修记录"${record.orderNo}"吗？`,
					success: async (res) => {
						if (res.confirm) {
							try {
								uni.showLoading({ title: '承认中...' });
								const ackRes = await acknowledgeFaultReport(record.reportNo);
								
								if (ackRes && ackRes.code === 200) {
									uni.hideLoading();
									uni.showToast({
										title: '承认成功',
										icon: 'success'
									});
									
									// 从列表中移除
									this.records.splice(index, 1);
								} else {
									throw new Error(ackRes.msg || '承认失败');
								}
							} catch (error) {
								uni.hideLoading();
								console.error('承认报修记录失败:', error);
								uni.showToast({
									title: error.message || '承认失败',
									icon: 'none'
								});
							}
						}
					}
				});
			},
			
			// 拒绝承认报修记录
			rejectAcknowledge(record, index) {
				uni.showModal({
					title: '确认拒绝承认',
					content: `确定要拒绝承认报修记录"${record.orderNo}"吗？拒绝后将重新分配给维修员。`,
					success: async (res) => {
						if (res.confirm) {
							try {
								uni.showLoading({ title: '拒绝承认中...' });
								const rejectRes = await rejectFaultReport(record.reportNo);
								
								if (rejectRes && rejectRes.code === 200) {
									uni.hideLoading();
									uni.showToast({
										title: '拒绝承认成功',
										icon: 'success'
									});
									
									// 从列表中移除
									this.records.splice(index, 1);
								} else {
									throw new Error(rejectRes.msg || '拒绝承认失败');
								}
							} catch (error) {
								uni.hideLoading();
								console.error('拒绝承认报修记录失败:', error);
								uni.showToast({
									title: error.message || '拒绝承认失败',
									icon: 'none'
								});
							}
						}
					}
				});
			},
			
			// 删除报修记录
			deleteRecord(record, index) {
				uni.showModal({
					title: '确认删除',
					content: `确定要删除报修记录"${record.orderNo}"吗？`,
					success: async (res) => {
						if (res.confirm) {
							try {
								uni.showLoading({ title: '删除中...' });
								const delRes = await delFaultReport(record.reportNo);
								
								if (delRes && delRes.code === 200) {
									uni.hideLoading();
									uni.showToast({
										title: '删除成功',
										icon: 'success'
									});
									
									// 从列表中移除
									this.records.splice(index, 1);
								} else {
									throw new Error(delRes.msg || '删除失败');
								}
							} catch (error) {
								uni.hideLoading();
								console.error('删除报修记录失败:', error);
				uni.showToast({
									title: error.message || '删除失败',
					icon: 'none'
								});
							}
						}
					}
				});
			},
			
			// 检查是否为维修主管
			isMaintenanceManager() {
				return permissionManager.hasRole('maintenance_manager');
			},
			
			// 检查是否可以指派维修
			canAssign(record) {
				// 只有待分配状态的报修单才能指派
				return record.status === 'PENDING_ASSIGN';
			},
			
			// 处理维修指派
			handleAssign(record) {
				// 跳转到维修管理页面进行指派
				uni.navigateTo({
					url: `/pages/repair/work-orders?reportNo=${record.reportNo}&assign=true`
				});
			}
		}
	}
</script>

<style scoped>
.container {
		min-height: 100vh;
	background-color: #f5f5f5;
	}
	
/* 状态栏占位 */
	.status-bar {
	background-color: #fff;
	}
	
/* 搜索栏 */
.search-bar {
	background-color: #fff;
	padding: 12px 16px;
	border-bottom: 1px solid #eee;
}

.search-input {
		display: flex;
		align-items: center;
	background-color: #f5f5f5;
	border-radius: 20px;
	padding: 8px 16px;
	}
	
	.search-icon {
	font-size: 16px;
	margin-right: 8px;
		color: #999;
	}
	
.search-input input {
		flex: 1;
	font-size: 14px;
		color: #333;
	}
	
/* 记录列表 */
.drafts-list {
	padding: 12px 16px;
}

.draft-item {
		position: relative;
	margin-bottom: 12px;
	transition: transform 0.3s;
	overflow: hidden;
}

.draft-content {
	background-color: #fff;
	border-radius: 8px;
	padding: 16px;
	box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.draft-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
	margin-bottom: 12px;
	}
	
.draft-title {
	font-size: 16px;
	font-weight: bold;
		color: #333;
	}
	
	.status-badge {
	padding: 4px 12px;
	border-radius: 12px;
	font-size: 12px;
}

.status-badge.acknowledged {
	background-color: #67c23a;
	color: #fff;
	}
	
	.status-text {
	font-size: 12px;
}

.draft-info {
	margin-bottom: 12px;
}

.info-item {
	display: block;
	font-size: 14px;
		color: #666;
	margin-bottom: 6px;
}

.draft-footer {
		display: flex;
	justify-content: space-between;
	align-items: center;
	}
	
	.reporter-info {
		display: flex;
		align-items: center;
	}
	
	.reporter-avatar {
	width: 24px;
	height: 24px;
		border-radius: 50%;
	margin-right: 8px;
	}
	
	.reporter-name {
	font-size: 14px;
	color: #666;
	}
	
	.report-time {
	font-size: 12px;
		color: #999;
}

/* 滑动操作按钮 */
.swipe-actions {
	position: absolute;
	right: -120px;
	top: 0;
	height: 100%;
	display: flex;
	align-items: center;
}

.swipe-btn {
	width: 60px;
	height: 100%;
		display: flex;
	align-items: center;
	justify-content: center;
	color: #fff;
	font-size: 14px;
	border: none;
	padding: 0;
	border-radius: 0;
}

.swipe-btn.view {
	background-color: #409eff;
}

.swipe-btn.delete {
	background-color: #f56c6c;
}

.swipe-btn.acknowledge {
	background-color: #67c23a;
}

.swipe-btn.reject {
	background-color: #e6a23c;
}

.swipe-btn.assign {
	background-color: #409EFF;
}

/* 空状态 */
	.empty-state {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	padding: 60px 0;
	}
	
	.empty-icon {
	font-size: 64px;
	margin-bottom: 16px;
	}
	
	.empty-text {
	font-size: 14px;
		color: #999;
	}
</style>
